// API封装层 - 隐藏真实API地址
import apiConfig from './apiConfig.js'
class ApiWrapper {
  constructor() {
    this.baseURL = apiConfig.getBaseURLSync()
    this.timeout = 10000
    this.initialized = false
    this.init()
  }

  // 初始化
  async init() {
    try {
      await apiConfig.init()
      this.baseURL = apiConfig.baseURL
      this.initialized = true
    } catch (error) {
      console.warn('API封装层初始化失败:', error)
      this.initialized = true
    }
  }

  // 生成随机请求ID
  generateRequestId() {
    return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  // 构建请求URL - 使用现有的apiConfig
  buildUrl(endpoint) {
    // 确保apiConfig已初始化
    if (!this.initialized) {
      this.baseURL = apiConfig.getBaseURLSync()
    }
    
    // 使用apiConfig的getApiURL方法
    return apiConfig.getApiURL(endpoint)
  }

  // 添加安全请求头
  addSecurityHeaders(headers = {}) {
    const token = (typeof window !== 'undefined' && window.localStorage)
      ? localStorage.getItem('token')
      : null
    
    // 添加调试日志
    console.log('获取token:', token)
    
    const authHeader = token ? { 'Authorization': `Bearer ${token}` } : {}
    const finalHeaders = {
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      'X-Request-ID': this.generateRequestId(),
      'X-Client-Version': '1.0.0',
      ...authHeader,
      ...headers
    }
    
    // 添加调试日志
    console.log('最终请求头:', finalHeaders)
    
    return finalHeaders
  }

  // 通用请求方法
  async request(method, endpoint, data = null, options = {}) {
    // 等待初始化完成
    if (!this.initialized) {
      await this.init()
    }

    const url = this.buildUrl(endpoint)
    const headers = this.addSecurityHeaders(options.headers)
    
    const config = {
      method,
      headers,
      timeout: this.timeout,
      ...options
    }

    if (data && method !== 'GET') {
      // 检查数据类型，如果是FormData则不进行JSON序列化
      if (data instanceof FormData) {
        // 对于FormData，不设置Content-Type，让浏览器自动设置
        delete headers['Content-Type']
        config.body = data
      } else {
        config.body = JSON.stringify(data)
      }
    }

    // 添加调试信息
    console.log(`API请求详情:`, {
      method,
      endpoint,
      url,
      headers: headers,
      data: data
    })

    try {
      const response = await fetch(url, config)
      
      // 检查响应状态
      if (!response.ok) {
        console.error(`API请求失败: ${method} ${endpoint}`, {
          status: response.status,
          statusText: response.statusText,
          url: url
        })
       
        // 处理401未授权错误（token过期）
        if (response.status === 401) {
          console.warn('Token已过期，正在跳转到登录页面...')
          // 清除本地存储的token
          if (typeof window !== 'undefined' && window.localStorage) {
            localStorage.removeItem('token')
            localStorage.removeItem('user')
          }
          // 跳转到登录页面
          if (typeof window !== 'undefined' && window.location) {
            window.location.href = '/login'
          }
        }
       
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      // 兼容无内容响应（例如 204/205）与空响应体
      if (response.status === 204 || response.status === 205) {
        if (import.meta.env.DEV) {
          console.log(`API ${method} ${endpoint} 成功:`, {
            requestId: headers['X-Request-ID'],
            status: response.status,
            data: null
          })
        }
        return null
      }

      const contentType = response.headers.get('content-type') || ''
      const rawText = await response.text()
      let result = null

      if (rawText && rawText.trim().length > 0) {
        if (contentType.includes('application/json')) {
          try {
            result = JSON.parse(rawText)
          } catch (parseError) {
            console.warn('JSON解析失败，返回原始文本:', parseError)
            result = rawText
          }
        } else {
          result = rawText
        }
      } else {
        result = null
      }
      
      // 记录请求日志（生产环境可关闭）
      if (import.meta.env.DEV) {
        console.log(`API ${method} ${endpoint} 成功:`, {
          requestId: headers['X-Request-ID'],
          status: response.status,
          data: result
        })
      }

      return result
    } catch (error) {
      console.error(`API ${method} ${endpoint} 请求失败:`, error)
      // 如果是401错误，已经在上面处理了跳转，这里不再重复处理
      throw error
    }
  }

  // GET请求
  async get(endpoint, params = null, options = {}) {
    console.log(endpoint);
    
    // 如果有参数，构建查询字符串
    let url = endpoint;
    if (params && typeof params === 'object') {
      const queryParams = new URLSearchParams();
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined && params[key] !== null) {
          // 处理嵌套对象，如 where: {project_id: 1}
          if (typeof params[key] === 'object' && !Array.isArray(params[key])) {
            Object.keys(params[key]).forEach(nestedKey => {
              queryParams.append(`${key}[${nestedKey}]`, params[key][nestedKey]);
            });
          } else {
            queryParams.append(key, params[key]);
          }
        }
      });
      const queryString = queryParams.toString();
      if (queryString) {
        url = `${endpoint}?${queryString}`;
      }
    }
    
    const res = await this.request('GET', url, null, options);
    console.log(res);
    return res;
  }

  // POST请求
  async post(endpoint, data, options = {}) {
    return this.request('POST', endpoint, data, options)
  }

  // PUT请求
  async put(endpoint, data, options = {}) {
    return this.request('PUT', endpoint, data, options)
  }

  // DELETE请求
  async delete(endpoint, options = {}) {
    return this.request('DELETE', endpoint, null, options)
  }

  // 分页查询
  async getPaginated(endpoint, page = 1, pageSize = 10, filters = {}) {
    const params = new URLSearchParams({
      page: page.toString(),
      pageSize: pageSize.toString(),
      ...filters
    })
    
    return this.get(`${endpoint}?${params.toString()}`)
  }

  // 按项目ID查询
  async getByProject(endpoint, projectId, page = 1, pageSize = 1000) {
    return this.getPaginated(endpoint, page, pageSize, {
      'where[project_id]': projectId
    })
  }
}

// 创建API实例
const apiWrapper = new ApiWrapper()

// 导出API方法
export const api = {
  // 直接请求方法
  get: (endpoint, params = null, options = {}) => apiWrapper.get(endpoint, params, options),
  post: (endpoint, data, options = {}) => apiWrapper.post(endpoint, data, options),
  put: (endpoint, data, options = {}) => apiWrapper.put(endpoint, data, options),
  delete: (endpoint, options = {}) => apiWrapper.delete(endpoint, options),

  // 项目相关
  project: {
    list: (params) => apiWrapper.get('/api/data/project', params),
    create: (data) => apiWrapper.post('/api/data/project', data),
    update: (id, data) => apiWrapper.put(`/api/data/project/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project/${id}`),
    detail: (id) => apiWrapper.get(`/api/data/project/${id}`)
  },

  // 项目进度
  projectSchedule: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_schedule', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_schedule', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_schedule/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_schedule/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_schedule', projectId)
  },

  // 项目权重
  projectPhaseWeight: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_phase_weight', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_phase_weight', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_phase_weight/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_phase_weight/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_phase_weight', projectId)
  },

  // 项目状态
  projectStatus: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_status', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_status', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_status/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_status/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_status', projectId)
  },

  // 里程碑
  milestone: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_milestone', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_milestone', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_milestone/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_milestone/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_milestone', projectId)
  },

  // 变更记录
  changeRecord: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_change', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_change', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_change/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_change/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_change', projectId)
  },

  // 问题汇总
  issueSummary: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_issue', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_issue', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_issue/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_issue/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_issue', projectId)
  },

  // 经验总结
  experienceSummary: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_experience', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_experience', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_experience/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_experience/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_experience', projectId)
  },

  // 文档管理
  documents: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/project_documents', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/project_documents', data),
    update: (id, data) => apiWrapper.put(`/api/data/project_documents/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/project_documents/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/project_documents', projectId),
    upload: (formData) => apiWrapper.post('/api/upload/document', formData)
  },

  // 人力资源
  humanResource: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/resource_plan', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/resource_plan', data),
    update: (id, data) => apiWrapper.put(`/api/data/resource_plan/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/resource_plan/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/resource_plan', projectId)
  },

  // 干系人
  stakeholder: {
    list: (page, pageSize) => apiWrapper.getPaginated('/api/data/stakeholder', page, pageSize),
    create: (data) => apiWrapper.post('/api/data/stakeholder', data),
    update: (id, data) => apiWrapper.put(`/api/data/stakeholder/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/stakeholder/${id}`),
    byProject: (projectId) => apiWrapper.getByProject('/api/data/stakeholder', projectId)
  },

  // 用户管理
  user: {
    list: (params) => apiWrapper.get('/api/data/User', params),
    create: (data) => apiWrapper.post('/api/data/User', data),
    update: (id, data) => apiWrapper.put(`/api/data/User/${id}`, data),
    delete: (id) => apiWrapper.delete(`/api/data/User/${id}`),
    detail: (id) => apiWrapper.get(`/api/data/User/${id}`),
    login: (credentials) => apiWrapper.post('/api/auth/login', credentials),
    logout: () => apiWrapper.post('/api/auth/logout'),
    profile: () => apiWrapper.get('/api/auth/profile')
  }
}

export default api 